<template>
  <view class="tn-shop-order-list">
    <tn-custom bg-color="bg-white">
      <block slot="left">
        <view class='action border-custom text-white' :style="'width:' + Custom.width + 'px;height:' + Custom.height + 'px;margin-left:calc(750rpx - ' + Custom.right + 'px)'"
          @click="goBack">
          <text class='cuIcon-back'></text>
          <text class='cuIcon-homefill'></text>
        </view>
      </block>
    </tn-custom>

    <scroll-view scroll-x class="bg-white nav" style="position: fixed;z-index: 9999;background-color: #FFFFFF;" :style="[{marginTop: 0 + 'px'}]"
      :scroll-left="scrollLeft">
      <view class="flex text-center">
        <view v-for="(type_item,type_index) in orderType" :key="type_index" class="cu-item flex-sub" :class="type_item.type==curType?'text-orange cur text-xl text-bold':''"
          @click="switchOrderType(type_item.type, type_index)">
          {{ type_item.title }}
        </view>
      </view>
    </scroll-view>

    <view v-if="paginateData.length == 0 && isLoadAll">
      <view class="flex justify-center align-center no-order">
        <view>
          <view class="flex justify-center image">
            <image src="/static/images/no-order.png" mode="heightFix" style="height: 100px;"></image>
          </view>
          <view class="title"><text>您还没有相关的订单</text></view>
        </view>
      </view>
    </view>

    <view v-else :style="[{marginTop: 100 + 'rpx'}]">
      <view v-for="(order_item, order_index) in paginateData" :key="order_index" class="cu-card case order">
        <view class="cu-item" @click="viewOrderDetail(order_item.id)">
          <view class="flex padding justify-between align-center title">
            <view class="text-black text-lg text-blod">{{ order_item.order_no }}</view>
            <view class="margin-left text-orange">{{ orderStatusValue(order_item.status, order_item.virtual_product) }}</view>
            <!-- <view class="margin-left text-orange" v-if="order_item.status == 2">等待卖家发货</view>
            <view class="margin-left text-orange" v-if="order_item.status == 3">订单支付失败</view>
            <view class="margin-left text-orange" v-if="order_item.status == 4">订单关闭</view>
            <view class="margin-left text-orange" v-if="order_item.status == 5">等待微信退款到账</view>
            <view class="margin-left text-orange" v-if="order_item.status == 9">等待买家收货</view>
            <view class="margin-left text-orange" v-if="order_item.status == 10">等待卖家确认退款</view>
            <view class="margin-left text-orange" v-if="order_item.status == 11">交易完成</view>
            <view class="margin-left text-orange" v-if="order_item.status == 12">支付超时</view> -->
          </view>
          <tn-show-product-info :product-data="order_item.product"></tn-show-product-info>

          <view class="flex justify-end align-center price">
            <view class="text-gray">
              <text class="price-title">总价</text><text class="price-unit">¥</text><text class="price-integer">{{ order_item.amount | priceInteger}}</text><text
                class="price-decimal">.{{ order_item.amount | priceDecimal}}</text>，<text class="price-title">优惠</text><text
                class="price-unit">¥</text><text class="price-integer">0</text><text class="price-decimal">.00</text></view>
            <view class="text-black padding-left-sm"><text class="price-title">实付款</text><text class="price-unit">¥</text><text
                class="price-integer">{{ order_item.amount | priceInteger}}</text><text class="price-decimal">.{{ order_item.amount | priceDecimal}}</text></view>
          </view>

          <view class="flex padding justify-between align-center operation">
            <view></view>
            <view class="btn">
              <!-- 注意防止点击事件冒泡 -->
              <button class="cu-btn line-gray round shadow-blur" @tap.native.stop="viewOrderDetail(order_item.id)">查看订单</button>
              <button
                v-if="order_item.virtual_product == 1 && order_item.status == 2"
                class="cu-btn line-gray round shadow-blur"
                open-type="contact"
                :show-message-card="true"
                :send-message-title="order_item.product[0].product_title + '购买后服务'"
                :send-message-img="order_item.product[0].product_image.prefix"
                :send-message-path="'/tn_shop/product_detail/product_detail?id=' + order_item.product[0].specs_id"
                @tap.native.stop=""
              >
                联系客服
              </button>
              <button v-if="[4,11,12].indexOf(order_item.status) != -1" class="cu-btn line-gray round shadow-blur" @tap.native.stop="deleteOrder(order_item.id)">删除订单</button>
              <button v-if="order_item.status == 1" class="cu-btn line-gray round shadow-blur" @tap.native.stop="closeOrder(order_item.id)">关闭订单</button>
              <button v-if="[9,14].indexOf(order_item.status) != -1" class="cu-btn line-gray round shadow-blur" @tap.native.stop="confirmReceiptOrder(order_item.id)">确认收货</button>
              <button v-if="order_item.status == 1" class="cu-btn line-gray round shadow-blur" @tap.native.stop="payOrder(order_item.id)">立即付款</button>
            </view>
          </view>
        </view>
      </view>
    </view>

    <tn-wx-login :show="showLogin" desc="用户记录您的登录信息" @closeLoginModal="closeLoginModal" @getUserInfo="getUserInfo"></tn-wx-login>

  </view>
</template>

<script>
  import TnShowProductInfo from '../components/tn-show-product-info/tn-show-product-info'
  import {
    checkUserScope,
    getUserInfo
  } from '@/utils/user.js'
  import {
    getTNShopOrderList,
    closeTNShopOrder,
    deleteTNShopOrder,
    confirmReceiptTNShopOrder,
    setTNShopAllowDeliverySubscribe
  } from '@/api/tn-shop-order.js'
  import {
    payTNShopOrder
  } from '@/api/pay.js'

  const util = require('@/utils/util')

  export default {
    name: 'TnShopOrderList',
    components: { TnShowProductInfo },
    data() {
      return {
        Custom: this.Custom,
        CustomBar: this.CustomBar,
        curType: 0,
        scrollLeft: 0,
        from: '', // 记录从那个页面来订单列表
        orderType: [{
            title: '全部',
            type: 0
          },
          {
            title: '待付款',
            type: 1
          },
          {
            title: '待发货',
            type: 2
          },
          {
            title: '待收货',
            type: '9,14'
          },
          {
            title: '待退款',
            type: 10
          },
          {
            title: '已完成',
            type: 11
          }
        ],
        orderStatusTitle: [
          { status: 1, title: '等待买家付款'},
          { status: 2, title: '等待卖家发货'},
          { status: 3, title: '订单支付失败'},
          { status: 4, title: '订单关闭'},
          { status: 5, title: '等待微信退款到账'},
          { status: 6, title: '退款完成'},
          { status: 7, title: '退款异常'},
          { status: 8, title: '退款关闭'},
          { status: 9, title: '等待买家收货'},
          { status: 10, title: '等待卖家确认退款'},
          { status: 11, title: '交易完成'},
          { status: 12, title: '支付超时'},
          { status: 13, title: '取消退款申请'},
          { status: 14, title: '等待用户确认收货'},
        ],                                // 订单状态标题
        virtualProductOrderStatusTitle: [
          { status: 1, title: '等待买家付款'},
          { status: 2, title: '联系卖家进行服务'},
          { status: 3, title: '订单支付失败'},
          { status: 4, title: '订单关闭'},
          { status: 5, title: '等待微信退款到账'},
          { status: 6, title: '退款完成'},
          { status: 7, title: '退款异常'},
          { status: 8, title: '退款关闭'},
          { status: 9, title: '等待用户确认服务完成'},
          { status: 10, title: '等待卖家确认退款'},
          { status: 11, title: '交易完成'},
          { status: 12, title: '支付超时'},
          { status: 13, title: '取消退款申请'},
          { status: 14, title: '等待用户确认服务完成'},
        ],                                // 服务商品订单状态标题
        paginateData: [], // 订单列表数据
        pageIndex: 1, // 当前数据的页码
        isLoadAll: false, //是否全部已经加载完毕
        checkUserScopeFlag: false, //用户是否已经授权
        showLogin: false, //打开登陆框
      };
    },
    onLoad(options) {
      this.from = options.from || ''
      this._loadData()
    },
    onReachBottom() {
      if (this.isLoadAll) {
        return
      }
      this.pageIndex++
      this._getOrderListData()
    },
    computed: {
      
    },
    filters: {
      // 金额显示过滤器(取出整数)
      priceInteger(n = 0.00) {
        if (typeof n == "string") {
          n = parseFloat(n)
        }
        n = n.toFixed(2)
        n = n.toString()
        return n.split(".")[0]
      },
      // 金额显示过滤器(取出小数)
      priceDecimal(n = 0.00) {
        if (typeof n == "string") {
          n = parseFloat(n)
        }
        n = n.toFixed(2)
        n = n.toString()
        return n.split(".")[1]
      }
    },
    methods: {

      // 切换订单类型
      switchOrderType(type, index) {
        this.curType = type
        this.scrollLeft = (index - 1) * 60

        this._refreshCurTypeListData()
      },
      
      // 跳转到订单详情页面
      viewOrderDetail(id) {
        uni.$once("refresh_order_list", () => {
          this._refreshCurTypeListData()
        })
        uni.navigateTo({
          url: '/tn_shop/order_detail/order_detail?id=' + id
        })
      },
      
      // 删除订单
      deleteOrder(id) {
        this._showConfirmModal('操作订单提醒', '确定需要删除订单吗?', () => {
          deleteTNShopOrder({
            id
          }).then((response) => {
            const { msg } = response
            this._showOperationOrderTips(msg, () => {
              this._refreshCurTypeListData()
            })
          }).catch(() => {
            this._showOperationOrderTips('删除订单失败')
          })
        })
      },
      
      // 关闭订单
      closeOrder(id) {
        this._showConfirmModal('操作订单提醒', '确定需要关闭订单吗?', () => {
          closeTNShopOrder({
            id
          }).then((response) => {
            const { msg } = response
            this._showOperationOrderTips(msg, () => {
              this._refreshCurTypeListData()
            })
          }).catch(() => {
            this._showOperationOrderTips('关闭订单失败')
          })
        })
      },
      
      // 确认收货
      confirmReceiptOrder(id) {
        this._showConfirmModal('操作订单提醒', '确定已经收到货物了吗?', () => {
          confirmReceiptTNShopOrder({
            id
          }).then((response) => {
            const { msg } = response
            this._showOperationOrderTips(msg, () => {
              this._refreshCurTypeListData()
            })
          }).catch(() => {
            this._showOperationOrderTips('订单确认收货失败')
          })
        })
      },
      
      // 对订单进行支付操作
      payOrder(id) {
        // 根据订单id判读当前的订单是否为虚拟订单
        const is_virtual_product_order = this.paginateData.findIndex((item) => {
          if(item.id == id && item.virtual_product == 1) {
            return true;
          }
        })
        payTNShopOrder({
          id
        }).then((response) => {
          const { data } = response
          uni.requestPayment({
            provider: 'wxpay',
            timeStamp: data.timeStamp,
            nonceStr: data.nonceStr,
            package: data.package,
            signType: data.signType,
            paySign: data.paySign,
            success: (res) => {
              this._checkDeliverySubscribe(data.order_no, () => {
                setTimeout(() => {
                  if(is_virtual_product_order != -1) {
                    uni.showModal({
                      showCancel:false,
                      title: "购买提示",
                      content: "当前购买的是服务商品，请购买后点击联系客服进行服务",
                      success: (res) => {
                        if(res.confirm) {
                          this._refreshCurTypeListData()
                        }
                      }
                    })
                  } else {
                    this._refreshCurTypeListData()
                  }
                }, 1500)
              })
              uni.showToast({
                title: '支付成功...',
                icon: 'none'
              })
            },
            fail: async (err) => {
              uni.showToast({
                title: '支付失败',
                icon: 'none'
              })
            }
          })
        })
      },

      //获取用户登陆状态
      getUserInfo() {
        if (res != null) {
          updateUserInfoToServer(res).then(() => {
            this.checkUserScopeFlag = true;
            util.showTips('登陆成功', '请继续执行上一步操作');
            this.closeLoginModal()
          }).catch(() => {
            util.showTips('授权提示', '获取授权失败')
            this.closeLoginModal()
          })
        } else {
          this.closeLoginModal()
        }
      },

      // 订单列表默认跳转到我的页面
      goBack() {
        if (this.from == 'my') {
          uni.navigateBack({
            delta: 1
          })
        } else {
          uni.navigateTo({
            url: '/pages/index/index?tab=my'
          })
        }
      },

      // 关闭登录窗口
      closeLoginModal() {
        // console.log('close Login');
        this.showLogin = false

      },
      
      // 获取当前状态对应的标题
      orderStatusValue(status, virtual_product) {
        let status_value = ''
        if (virtual_product == 1) {
          status_value = this.virtualProductOrderStatusTitle.filter((item) => {
            return item.status == status
          })
        } else {
          status_value = this.orderStatusTitle.filter((item) => {
            return item.status == status
          })
        }
        // console.log(status_value);
        return status_value.length > 0 ? status_value[0].title : ''
      },

      // 加载数据
      _loadData() {
        this._checkUserScope().then(() => {
          this._getOrderListData()
        }).catch(() => {
          // 如果用户还没有登录授权，直接返回
          this.goBack()
        })
      },
      
      // 重新加载当前订单类型数据
      _refreshCurTypeListData() {
        // 清空之前的订单列表数据，然后再获取
        this.paginateData = []
        this.pageIndex = 1
        this.isLoadAll = false
        this._getOrderListData()
      },

      // 获取订单列表数据
      _getOrderListData() {
        uni.showLoading({
          title: '加载中...',
          mask: true
        })
        this._getOrderPaginationData().then((res) => {
          uni.hideLoading()
          //判断是否还有数据返回，如果没有则证明已经全部加载完成
          if (res.data && res.data.length > 0) {
            // 合并数组
            this.paginateData.push.apply(this.paginateData, res.data);

          } else {
            this.isLoadAll = true; //全部加载完毕
            this.pageIndex = 1;
          }
        }).catch(() => {
          uni.hideLoading()
        })
      },

      // 根据订单类型获取用户订单列表分页数据
      _getOrderPaginationData() {
        return new Promise((resolve, reject) => {
          getTNShopOrderList({
            page: this.pageIndex,
            limit: 4,
            type: this.curType
          }).then((response) => {
            // console.log(response);
            const { data } = response
            // 对数据进行预处理，判断是否为服务商品订单
            data.data.forEach((item, index) => {
              const have_virtual_product = item.product.some((product_item) => {
                return product_item.virtual_product == 1
              })
              data.data[index]['virtual_product'] = have_virtual_product ? 1 : 0
            })
            resolve(data)
          }).catch((err) => {
            // console.log(err);
            if (err.errorCode != 50004) {
              uni.showToast({
                title: '加载失败',
                icon: 'none',
              });
            }
            resolve({
              data: []
            });
          })
        })
      },
      
      // 如果支付成功询问用户是否推送发货通知
      async _checkDeliverySubscribe(order_no, success_function) {
        const allow_ids = await util.checkSubscribeSetting(['4wDuEywMFodW26lQEMuMPQpOyPHLd7Ofs0eAonyyrY8'])
        
        if (allow_ids.indexOf('4wDuEywMFodW26lQEMuMPQpOyPHLd7Ofs0eAonyyrY8') != -1) {
          setTNShopAllowDeliverySubscribe({
            order_no,
            allow_delivery_subscribe: 1
          }).then(() => {
            if (success_function && typeof(success_function) === 'function') {
              success_function()
            }
          })
        } else {
          if (success_function && typeof(success_function) === 'function') {
            success_function()
          }
        }
      },
      
      // 显示订单操作确认提示框
      _showConfirmModal(title = '', content = '', success_function) {
        uni.showModal({
          title,
          content,
          success: (res) => {
            if (res.confirm) {
              if (success_function && typeof(success_function) === 'function') {
                success_function()
              }
            }
          }
        })
      },
      
      // 订单操作信息提示框
      _showOperationOrderTips(title = '', end_function) {
        uni.showToast({
          icon: 'none',
          title,
          success: () => {
            setTimeout(() => {
              if (end_function && typeof(end_function) === 'function') {
                end_function()
              }
            }, 1500)
          }
        })
      },

      /**
       * 检查当前用户的权限
       */
      _checkUserScope() {
        return new Promise((resolve, reject) => {
          checkUserScope().then((res) => {
            this.checkUserScopeFlag = res
            resolve();
          }).catch((res) => {
            this.checkUserScopeFlag = res
            reject();
          });
        });
      }
    }
  }
</script>

<style lang="scss" scoped>
  .tn-shop-order-list {
    background-color: #f1eef3;

    .no-order {
      width: 100%;
      height: calc(100vh - 115rpx);

      .image .title {
        display: block;
      }
    }

    .order {
      .title {
        // padding-bottom: 0px;
        border-bottom: 0.7px solid #e9e6eb;
      }

      .price {
        padding-right: 20px;
      }

      .operation {
        padding-right: 20px;

        .btn button {
          margin-left: 10px;
          background-color: transparent;
          color: #aaaaaa;
          line-height: 45rpx;
          font-size: 25rpx;
          height: 50rpx;
        }

        .btn button:last-child {
          color: #e54d42;
        }
      }

      .price-title {
        letter-spacing: 2px;
        font-size: 16px;
      }

      .price-unit {
        letter-spacing: 2px;
        font-size: 12px;
      }

      .price-integer {
        font-size: 16px;
      }

      .price-decimal {
        font-size: 12px;
      }
    }
  }
</style>
